package com.heima.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        HashMap<String, Object> map = new HashMap<>();
        //游客登陆
        if (StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPhone())){
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
        //正常登录
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(dto.getPhone()),ApUser::getPhone,dto.getPhone());
        ApUser user = apUserMapper.selectOne(wrapper);
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //比对密码
        String password = dto.getPassword();
        String passwordFromDb = user.getPassword();
        String salt = user.getSalt();
        String passwordAfter = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        //密码错误
        if (!passwordAfter.equals(passwordFromDb)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //返回数据
        user.setSalt("");
        user.setPassword("");
        String token = AppJwtUtil.getToken(user.getId().longValue());
        map.put("user",user);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}